<?php

namespace app\admin\controller\xilujob;

use app\admin\model\User;
use app\admin\model\xilujob\XilujobUser;
use app\common\controller\Backend;
use app\admin\model\User AS UserModel;
use think\Db;
use think\Exception;
use think\exception\PDOException;

/**
 * 会员管理
 *
 * @icon fa fa-circle-o
 */
class Member extends Backend
{
    protected $noNeedRight = ['exist'];
    /**
     * XilujobUser模型对象
     * @var \app\admin\model\xilujob\Member
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\xilujob\Member;
        $this->view->assign("sourceList", $this->model->getSourceList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['user'=>function($q){
                    $q->withField(['id','username','status','nickname','mobile','email','avatar']);
                },'xilujobuser'])
                ->where($where)
                ->whereIn('xilujobuser.source',[XilujobUser::SOURCE_REGISTER,XilujobUser::SOURCE_BACKEND])
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加用户
     */
    public function add() {
        if($this->request->isPost()) {
            $userData = $this->request->post("user/a");
            //$userData['city_id'] = $this->siteCity->city_id;
            $groupData = $this->request->post('member/a');
            if($userData['mobile']) {
                $user = User::where('mobile', $userData['mobile'])->find();
            }
            if(!$user && $userData['email']){
                $user = User::where('email', $userData['email'])->find();
            }

            Db::startTrans();
            try {
                $member = XilujobUser::add_user(1, $userData, $groupData,[],$user??[]);
            }catch (Exception $exception){
                Db::rollback();
                $this->error($exception->getMessage());
            }
            Db::commit();
            $this->success();
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {

        $member = $this->model->get($ids);
        if (!$member) {
            $this->error(__('No Results were found'));
        }
        $user = $member->user;
        if($this->request->isPost()) {
            $userData = $this->request->post("user/a");
            $groupData = $this->request->post('member/a');
            Db::startTrans();
            try {
                $member = XilujobUser::edit_user($user->id, 1, $userData, $groupData);
            }catch (Exception $exception){
                Db::rollback();
                $this->error($exception->getMessage());
            }
            Db::commit();

            $this->success();
        }
//        if($user){
//            $user->mobile = preg_replace('/(\d{3})\d{4}(\d{4})/', '$1****$2', $user->mobile);
//            if(preg_match("/^1[345789]\d{9}$/", $user->username)){
//                $user->username = preg_replace('/(\d{3})\d{4}(\d{4})/', '$1****$2', $user->mobile);
//            }
//
//        }

        $this->assign('member', $member);
        $this->assign('user', $user);
        return $this->fetch();

    }



    public function exist() {
        $type = $this->request->param('type','member');
        $mobile = $this->request->post('user.mobile');
        $email = $this->request->post('user.email');
        $username = $this->request->post('user.username');
        if($mobile) {
            $count = UserModel::where('mobile', $mobile);
        }else if($email){
            $count = UserModel::where('email', $email);
        }else if($username){
            $count = UserModel::where('username', $username);
        }else {
            $this->error('参数错误');
        }
        $id = $this->request->post('id');
        if($id) {
            $count->where('id','<>',$id);
        }
        $count = $count->select();
        if($type == 'company' && count($count) > 0){
            $count = \app\admin\model\xilujob\CompanyProfile::where('user_id',$count[0]['id'])->count();
        }else{
            $count = count($count);
        }
        if($count) {
            $this->error('账号已注册');
        }else {
            $this->success('可以使用');
        }
    }


    public function multi($ids = "")
    {
        $ids = $ids ? $ids : $this->request->param("ids");
        if ($ids) {
            $ids = \app\admin\model\xilujob\CompanyProfile::where('id','in',$ids)->column('user_id');
            if ($this->request->has('params')) {
                parse_str($this->request->post("params"), $values);

                $values = array_intersect_key($values, array_flip((array) 'status'));
                if ($values || $this->auth->isSuperAdmin()) {
                    $adminIds = $this->getDataLimitAdminIds();
                    if (is_array($adminIds)) {
                        $this->model->where($this->dataLimitField, 'in', $adminIds);
                    }
                    $count = 0;
                    Db::startTrans();
                    try {
                        $list = User::where('id', 'in', $ids)->select();
                        foreach ($list as $index => $item) {
                            $count += $item->allowField(true)->isUpdate(true)->save($values);
                        }
                        Db::commit();
                    } catch (PDOException $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    } catch (Exception $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    }
                    if ($count) {
                        $this->success();
                    } else {
                        $this->error(__('No rows were updated'));
                    }
                } else {
                    $this->error(__('You have no permission'));
                }
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

}
